<?php

  class Dice
  {
    private $values = array();
    private $valueCount = array();
    private $numInOrder = 0;
    
    public function __construct()
    {
      //initialize values
      for ($i=1; $i<=YachtDice::$numDice; $i++) {
        $this->values[$i] = $this->roll(YachtDice::$diceSides);
      }
      
      //override chosen values with GET params, if they exist (for testing)
      if (isset($_REQUEST['die1'])) {
        $this->values[1] = (int)$_REQUEST['die1'];
      }
      if (isset($_REQUEST['die2'])) {
        $this->values[2] = (int)$_REQUEST['die2'];
      }
      if (isset($_REQUEST['die3'])) {
        $this->values[3] = (int)$_REQUEST['die3'];
      }
      if (isset($_REQUEST['die4'])) {
        $this->values[4] = (int)$_REQUEST['die4'];
      }
      if (isset($_REQUEST['die5'])) {
        $this->values[5] = (int)$_REQUEST['die5'];
      }
      
      //initialize sorted values
      $sortedValues = $this->values;
      sort($sortedValues);
      $sortedUniqueValues = array_unique($sortedValues);

      //initialize the number of values in order
      $key = 0;
      $inOrder = array();
      $lastDieValue = $sortedUniqueValues[0]-1;
      $loopCount = 0;
      foreach ($sortedUniqueValues as $sortedUniqueDie) {
        if ($sortedUniqueDie == $lastDieValue+1) {
          if (!isset($inOrder[$key])) {
            $inOrder[$key] = 0;
          }
          $inOrder[$key]++;
          if ($loopCount == YachtDice::$numDice-1) {
            $inOrder[$key]++;
          }
        } else {
          $key++;
        }
        $lastDieValue = $sortedUniqueDie;
        $loopCount++;
      }
      rsort($inOrder);
      $this->numInOrder = $inOrder[0];
      
      //initialize value count
      foreach ($this->values as $die) {
        if (!isset($this->valueCount[$die])) {
          $this->valueCount[$die] = 0;
        }
        $this->valueCount[$die] += 1;
      }
      rsort($this->valueCount, SORT_NUMERIC);
    }
    
    public function getValues()
    {
      return $this->values;
    }
    
    public function getValueCount()
    {
      return $this->valueCount;
    }
    
    public function getNumInOrder()
    {
      return $this->numInOrder;
    }
    
    private function roll($sides)
    {
      $sides = (int)$sides;
      if ($sides > 0) {
        return rand(1, $sides);
      } else {
        return null;
      }
    }
  }